﻿using System;
using System.Collections.Generic;
using System.Web.Hosting;
using System.Xml;

using umbraco;

namespace TheOutfield.UmbExt.DocumentSorter
{
    public class DocumentSorterConfig
    {
        #region Singleton

        private static DocumentSorterConfig _instance;

        public static DocumentSorterConfig Instance
        {
            get
            {
                if (_instance == null)
                    _instance = new DocumentSorterConfig();

                return _instance;
            }
        }

        private DocumentSorterConfig()
        {
            ConfigEntries = new Dictionary<string, List<DocumentSorterConfigEntry>>();

            LoadXmlConfig();
        }

        #endregion

        #region Properties

        public Dictionary<string, List<DocumentSorterConfigEntry>> ConfigEntries { get; set; }

        #endregion

        #region Methods

        private void LoadXmlConfig()
        {
            XmlDocument xmlConfig = new XmlDocument();
            xmlConfig.Load(HostingEnvironment.MapPath(GlobalSettings.Path + "/../config/documentSorter.config"));
            
            foreach (XmlNode xmlConfigEntry in xmlConfig.SelectNodes("/documentSorterConfig/add"))
            {
                if (xmlConfigEntry.NodeType == XmlNodeType.Element)
                {
                    var configEntry = new DocumentSorterConfigEntry()
                    {
                        Field = xmlConfigEntry.Attributes["field"].Value,
                        Type = (Type)Enum.Parse(typeof(Type), xmlConfigEntry.Attributes["type"].Value),
                        Order = (Order)Enum.Parse(typeof(Order), xmlConfigEntry.Attributes["order"].Value)
                    };

                    if (xmlConfigEntry.Attributes["docTypeAlias"] != null && !string.IsNullOrEmpty(xmlConfigEntry.Attributes["docTypeAlias"].Value))
                        configEntry.DocTypeAlias = xmlConfigEntry.Attributes["docTypeAlias"].Value;
                    else
                        configEntry.DocTypeAlias = "$_ALL";

                    if (xmlConfigEntry.Attributes["rootXpath"] != null)
                        configEntry.RootXPath = xmlConfigEntry.Attributes["rootXpath"].Value;

                    bool disableTreeRefresh = false;
                    if (xmlConfigEntry.Attributes["disableTreeRefresh"] != null)
                        bool.TryParse(xmlConfigEntry.Attributes["disableTreeRefresh"].Value, out disableTreeRefresh);

                    configEntry.DisableTreeRefresh = disableTreeRefresh;

                    if(!ConfigEntries.ContainsKey(configEntry.DocTypeAlias))
                        ConfigEntries.Add(configEntry.DocTypeAlias, new List<DocumentSorterConfigEntry>());

                    ConfigEntries[configEntry.DocTypeAlias].Add(configEntry);
                }

            }
        }

        #endregion
    }
}